package repositories

import (
	"chat/app/models"
	"encoding/json"
	"log"
	"math/rand"
	"time"

	"github.com/astaxie/beego"
	"github.com/astaxie/beego/logs"
	"github.com/astaxie/beego/orm"
)

//随机命名处理件
type MemberRepository struct {
	ChatName string
	models.Members
}

const letterBytes string = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"

const NameKey = "name"

func init() {
	log.Println("memberRepository init success")
}

//获取所有在线用户名
func (this *MemberRepository) GetOnlineList(app *beego.Controller) []orm.Params {
	o := orm.NewOrm()
	qs := o.QueryTable(this.Members)

	var lists []orm.Params
	qs.Exclude("name", this.ChatName).OrderBy("-last_login_at").Values(&lists)
	for key, item := range lists {
		color := "green"
		if 1 == key%3 {
			color = "blue"
		}

		var isOnlien, _ = item["IsOnline"].(int64)
		if isOnlien < 1 {
			color = "aero"
		}

		item["color"] = color
		lists[key] = item
	}

	return lists
}

//获取用户详细信息
func (this *MemberRepository) GetMemberInfo(memberId int64) models.Members {
	o := orm.NewOrm()
	member := models.Members{Id: memberId}
	o.Read(&member)

	return member
}

//下线处理
func (this *MemberRepository) DownOnline(memberId int64) {
	o := orm.NewOrm()
	member := models.Members{Id: memberId}
	o.Read(&member)
	member.IsOnline = 0
	o.Update(&member)
}

//上线处理
func (this *MemberRepository) UpOnline(memberId int64) {
	o := orm.NewOrm()
	member := models.Members{Id: memberId}
	o.Read(&member)
	member.IsOnline = 1
	o.Update(&member)
}

//获取当前用户名
func (this *MemberRepository) GetName(app *beego.Controller) map[string]interface{} {
	chatName := app.GetSession("chatName")
	if nil == chatName {
		chatName = this.getRandName()
		app.SetSession("chatName", chatName)
	}

	this.ChatName = chatName.(string)

	//数据库查看是否已存在
	o := orm.NewOrm()
	member := models.Members{Name: this.ChatName}

	err := o.Read(&member, "name")
	member.LoginIp = app.Ctx.Input.IP()
	member.IsOnline = 1
	if err == orm.ErrNoRows {
		//插入数据
		id, _ := o.Insert(&member)
		member.Id = id
	} else {
		//更新最后在线时间和 ip 状态
		o.Update(&member)
	}

	//struct 转 map
	var chatInfo = make(map[string]interface{})
	j, _ := json.Marshal(&member)
	json.Unmarshal(j, &chatInfo)

	logs.Info(chatInfo)

	return chatInfo
}

func (member *MemberRepository) getRandName() interface{} {
	b := make([]byte, 5)
	rand.Seed(time.Now().Unix())

	for i := 0; i <= 4; i++ {
		num := rand.Intn(52)
		b[i] = letterBytes[num]
	}
	return string(b)
}

/******************** 自定义方法 *********************************/
// 获取聊天朋友列表
func (member *MemberRepository) GetRooms(id int) []orm.Params {

	qb, _ := orm.NewQueryBuilder("mysql")
	// 构建查询对象
	qb.Select("c.*",
		"u_a.name AS name_a",
		"u_b.name AS name_b",
		"ud_a.avatar AS avatar_a",
		"ud_b.avatar AS avatar_b",
		"any_value(shop_a.shop_name) as shop_name_a",
		"any_value(shop_b.shop_name) as shop_name_b",
		"any_value(shop_a.shop_pic) as shop_pic_a",
		"any_value(shop_b.shop_pic) as shop_pic_b",
		"any_value(shop_a.id) as shop_id_a",
		"any_value(shop_b.id) as shop_id_b",
		"count(if(msg.member_id<>? and msg.if_read=0,true,null)) as unread_total",
	).
		From("kppw_chat c").
		InnerJoin("kppw_chat_message msg").On("c.`id` = msg.`chat_id`").
		InnerJoin("kppw_users u_a").On("c.`member_a` = u_a.`id`").
		InnerJoin("kppw_users u_b").On("c.`member_b` = u_b.`id`").
		LeftJoin("kppw_shop shop_a").On("c.`member_a` = shop_a.`uid`").
		LeftJoin("kppw_shop shop_b").On("c.`member_b` = shop_b.`uid`").
		LeftJoin("kppw_user_detail ud_a").On("c.`member_a` = ud_a.`uid`").
		LeftJoin("kppw_user_detail ud_b").On("c.`member_b` = ud_b.`uid`").
		Where("(c.member_a = ? or c.member_b = ?)").
		GroupBy("c.id").
		OrderBy("c.updated_at").Desc()

	// .Limit(10)
	// .Offset(0)
	sql := qb.String()

	o := orm.NewOrm()

	var lists []orm.Params
	num, err := o.Raw(sql, id, id, id).Values(&lists)
	log.Println(id, "::", sql, "---", lists)

	if err == nil && num > 0 {
		return lists
	}
	return lists

}

// 获取用户信息
func (member *MemberRepository) GetUserDetail(id int64) models.Users {
	log.Println("GetUserDetail")
	qb, _ := orm.NewQueryBuilder("mysql")
	// 构建查询对象
	qb.Select("u.id", "u.name", "ud.avatar", "s.id as shop_id", "s.shop_name").
		From("kppw_users u").
		LeftJoin("kppw_user_detail ud").On("ud.`uid` = u.`id`").
		LeftJoin("kppw_shop s").On("s.`uid` = u.`id`").
		Where("u.id = ?")
	sql := qb.String()

	o := orm.NewOrm()

	var user models.Users
	err := o.Raw(sql, id).QueryRow(&user)
	log.Println(id, "::", sql, "---", user)

	if err == nil {
		return user
	}
	return user

}
